package com.shenzhenai.jetpackcomposelayouts

import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasurePolicy
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
import com.shenzhenai.jetpackcomposelayouts.ui.theme.DN_Compose_LearnTheme

/**
 * @author huangzehui
 * @date 30/7/2025 下午10:39 周三
 * @description 仿 Column 组件
 */

@Composable
fun MyOwnColumn(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
    /**
     * measurePolicy 参数是一个 MeasurePolicy 接口，实现了     fun MeasureScope.measure(
     *         measurables: List<Measurable>,
     *         constraints: Constraints
     *     ): MeasureResult
     *
     * 这个方法的lambdas表达式，可以理解为实现了这个接口
     */

    /**
     * measurePolicy 参数，本质上是这样的
     */
//    val measurePolicy =  object : MeasurePolicy {
//        override fun MeasureScope.measure(
//            measurables: List<Measurable>,
//            constraints: Constraints
//        ): MeasureResult {
//            layout(0, 0) {
//
//            }
//        }
//
//    }

    Layout(modifier = modifier, content = content, measurePolicy = { measurables, constraints ->
        // 布局中需要测量的元素可能存在多个，所以这里一一测量
        // 测量元素
        val placeables = measurables.map { measurable: Measurable ->
            measurable.measure(constraints)
        }

        var yPosition = 0

        // 布局的大小
        layout(constraints.maxWidth, constraints.maxHeight) {

            for (placeable in placeables) {
                // 设置元素的位置
                placeable.placeRelative(x = 0, y = yPosition)
                yPosition += placeable.height
            }

        }
    })
}

@Composable
fun MyOwnColumnSample() {
    DN_Compose_LearnTheme {
        MyOwnColumn(modifier = Modifier.padding(8.dp)) {
            Text(text = "MyOwnColumn")
            Text(text = "place items")
            Text(text = "vertically.")
            Text(text = "We`ve done it by hand!")
        }
    }
}